<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          @input="changeValue"
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"/>
        <!-- 树形组件 -->
        <el-tree
          ref="deptFrom"
          node-key="id"
          @current-change="selectNode"
          :data="dataArr"
          :props="defaultProps"
          :highlight-current="true"
          default-expand-all
          :expand-on-click-node="false">
        </el-tree>
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employ'" size="mini" type="primary" @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini">excel导入</el-button>
          <el-button size="mini">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column prop="staffPhoto" label="头像" algin="center">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30"></el-avatar>
              <span class="username" v-else>{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名"></el-table-column>
          <el-table-column prop="mobile" label="手机号" sortable></el-table-column>
          <el-table-column prop="workNumber" label="工号" sortable></el-table-column>
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式 </span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门"></el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间" sortable></el-table-column>
          <el-table-column label="操作" wifth="280px">
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="确定删除吗？"
                @onConfirm="delBtn(row.id)"
              >
                <el-button style="margin-left: 10px" slot="reference" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 60px">
          <el-pagination
            layout="total, prev, pager, next"
            :page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            :total="total"
            @current-change="changePage"
          >
          </el-pagination>
        </el-row>
      </div>
    </div>
    <!--    放置角色弹层组件-->
    <el-dialog :visible.sync="showRole" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox :label="item.id" v-for="item in roleList" :key="item.id">{{ item.name }}</el-checkbox>
      </el-checkbox-group>
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="btnOk">确定</el-button>
          <el-button size="mini" @click="showRole=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {getDepartmentList} from '@/api/department'
import {getEmployeetList, delEmployee, getEnableRoleList, detailEmployee, getEmployRole} from '@/api/employee'
import {toTreeDate} from '@/utils'

export default {
  name: 'Employee',
  data() {
    return {
      dataArr: [], // 组织架构数据
      defaultProps: {
        label: 'name', // 显示的字段的名字
        children: 'children' // 读取子节点的字段名
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,
        page: 1,
        pagesize: 10,
        keyword: ''
      },
      list: [], // 员工列表数据
      total: 0,
      roleList: [], // 可以角色列表
      roleIds: [], // 用来多选框的双向绑定
      currentUserId: null, // 用来记录当前点击用户的id
      showRole: false // 用老控制角色弹层的显示
    }
  },
  created() {
    // 获取组织架构数据
    this.getList()
  },
  methods: {
    async getList() {
      const res = await getDepartmentList()
      this.dataArr = toTreeDate(res, 0)
      console.log(this.dataArr[0])
      // 初始化数据-获取首个节点
      this.queryParams.departmentId = this.dataArr[0].id
      // 设置选中节点
      // 树组件的渲染是异步的 要等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树组件渲染完毕
        this.$refs.deptFrom.setCurrentKey(this.queryParams.departmentId)
      })
      // 这个时候参数记录了id
      this.getEmployList()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1 // 设置为第一页
      this.getEmployList()
    },
    async getEmployList() {
      const {rows, total} = await getEmployeetList(this.queryParams)
      this.list = rows
      this.total = total
    },
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getEmployList()
    },
    // 输入值内容改变时触发
    changeValue() {
      // 防抖：单位时间内只执行最后一次
      // this的实例上赋值了一个timer属性（因为他不是响应式数据，不用来影响视图，所以不用定义到data里）
      clearTimeout(this.timer) // 清理上一次的定时器
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployList()
      }, 300)
    },
    async delBtn(id) {
      await delEmployee(id) // 只是删除了后端的数据，前端现在还没变
      this.$message.success('删除员工成功')
      // 如果删除的是最后一个数据
      if (this.list.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployList()
    },
    // 点击角色弹出层
    async btnRole(id) {
      this.roleList = await getEnableRoleList()
      // 记录当前点击的id 因为后面确定取消要存取给用户
      this.currentUserId = id
      const {roleIds} = await detailEmployee(id)
      this.roleIds = roleIds
      this.showRole = true
    },
    async btnOk() {
      await getEmployRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.showRole = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}

</style>
